import { order as orderApi } from "@mall/api-services"
import { Button, Card, Col, Descriptions, Rate, Row, Spin, Statistic, Table, Typography } from "antd"
import { ColumnProps } from "antd/es/table"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useCallback, useEffect, useState } from "react"
import { useParams } from "react-router-dom"
import Page from "../../components/page"
import { OrderCancelModal } from "./order-cancel"
import classes from "./order-detail.module.scss"
import { OrderDiscountsModal } from "./order-discounts"
import OrderShipments, { AddOrderShippingModal, EditOrderShippingModal } from "./order-shipments"
import { OrderStaffNotesModal } from "./order-staff-notes"
import { OrderStatusSteps } from "./order-status"

const { Title, Text } = Typography

const {
  Pending,
  AwaitingPayment,
  AwaitingFulfillment,
  PartiallyShipped,
  Shipped,
  AwaitingPickup,
  Cancelled,
  Completed,
} = orderApi.OrderStatus

export class TableOrderItem {
  public id: string = ""
  public name: string = ""
  public price: number = 0
  public quantity: number = 0
  public shippingStatus: boolean = false
  public shippingProvider: string = ""
  public trackingNumber: string = ""
  public discountAmount: string = ""
  public subtotalAmount: string = ""
  public productId: string = ""
  public variantId: string = ""
}

export default function OrderDetail() {
  const { orderId = "" } = useParams()
  const [order, setOrder] = useState(new orderApi.Order())
  const { shippedTime, items, status, shipments, shippingAddress, placingExpiredTime, paymentStatus, paymentMethod } = order
  const [loading, setLoading] = useState(false)

  const refreshOrder = useCallback(() => {
    setLoading(true)
    orderApi.OrderServiceV1
      .getOrder(orderId)
      .then(setOrder)
      .finally(() => setLoading(false))
  }, [orderId])

  useEffect(refreshOrder, [orderId])

  const [addShippingModalVisible, setAddShippingModalVisible] = useState(false)
  const [editShippingModalVisible, setEditShippingModalVisible] = useState(false)
  const [staffNotesModalVisible, setStaffNotesModalVisible] = useState(false)
  const [staffNotesModalLoading, setStaffNotesModalLoading] = useState(false)
  const [discountsModalVisible, setDiscountsModalVisible] = useState(false)
  const [cancelModalVisible, setCancelModalVisible] = useState(false)

  function handleChangeAddShippingModalVisible() {
    setAddShippingModalVisible(!addShippingModalVisible)
  }

  function handleChangeEditShippingModalVisible() {
    setEditShippingModalVisible(!editShippingModalVisible)
  }

  function handleChangeStaffNotesModalVisible() {
    setStaffNotesModalVisible(!staffNotesModalVisible)
  }

  function handleChangeDiscountsModalVisible() {
    setDiscountsModalVisible(!discountsModalVisible)
  }

  function handleChangeCancelModalVisible() {
    setCancelModalVisible(!cancelModalVisible)
  }

  const tableItems = _.map(items, item => {
    const shipment = _.find(shipments, aShipment => aShipment.containsItem(item))
    return _.assign(new TableOrderItem(), {
      id: item.id,
      name: item.name,
      price: item.price,
      quantity: item.quantity,
      discountAmount: item.discountAmount,
      subtotalAmount: item.subtotalAmount,
      shippingStatus: !_.isUndefined(shipment),
      shippingMethod: "快递",
      shippingProvider: shipment?.shippingProvider,
      trackingNumber: shipment?.trackingNumber,
      productId: item.productId,
      variantId: item.variantId,
    })
  })

  const orderItemsColumns: ColumnProps<TableOrderItem>[] = [
    {
      title: "商品",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "单价(元)",
      dataIndex: "price",
      key: "price",
      align: "right",
    },
    {
      title: "数量",
      dataIndex: "quantity",
      key: "quantity",
      align: "right",
    },
    {
      title: "优惠(元)",
      dataIndex: "discountAmount",
      key: "discountAmount",
      align: "right",
    },
    {
      title: "小计(元)",
      dataIndex: "subtotalAmount",
      key: "subtotalAmount",
      align: "right",
    },
    {
      title: "售后状态",
      dataIndex: "address",
      key: "address",
      align: "right",
      render: () => "-",
    }, {
      title: "发货状态",
      dataIndex: "shippingStatus",
      key: "shippingStatus",
      align: "right",
      render: (shippingStatus) => shippingStatus ? "已发货" : "未发货",
    },
  ]

  function renderPaymentStatus() {
    if (paymentStatus === "captured") {
      return "已支付"
    }
    return "待支付"
  }

  function renderPaymentMethod() {
    if (paymentMethod === "wxpay") {
      return "微信支付"
    }
    return "支付宝"
  }

  function handSaveStaffNotes(staffNotes: string) {
    setStaffNotesModalLoading(true)
    orderApi.OrderServiceV1
      .saveOrder({ id: orderId, staffNotes })
      .then(handleChangeStaffNotesModalVisible)
      .then(refreshOrder)
      .finally(() => setStaffNotesModalLoading(false))
  }

  return (
    <div className={classes.orderDetail}>
      <Page.Header title="订单详情" ghost={false}/>
      <Page.Content>
        <Spin spinning={loading}>
          <Card>
            <Row gutter={[24, 24]}>
              <Col span={24}>
                订单号 : {order.id} 下单时间 : {order.placedTime} 微信-商家微商城
              </Col>
            </Row>
            <Row gutter={[24, 24]} className={classes.orderStatuses} align="middle">
              <Col span={10} className={classes.orderStatus}>
                {
                  (_.isEqual(status, Pending) || _.isEqual(status, AwaitingPayment)) && <>
                    <Title level={4}>商品已拍下，等待买家付款</Title>
                    <Text>如买家未在
                      <Statistic.Countdown value={dayjs(placingExpiredTime).valueOf()} format="H时m分s秒"/>
                      内付款，订单将按照设置逾期自动关闭。</Text>
                    <div className={classes.orderStatusActions}>
                      <Button type="link" onClick={handleChangeDiscountsModalVisible}>改价</Button>
                      <Button type="link" onClick={handleChangeCancelModalVisible}>取消订单</Button>
                    </div>
                  </>
                }
                {
                  (_.isEqual(status, AwaitingFulfillment) || _.isEqual(status, PartiallyShipped)) && <>
                    <Title level={4}>等待商家发货</Title>
                    <Text>买家已付款至系统待结算账户，请尽快发货，否则买家有权申请退款。</Text>
                    <div className={classes.orderStatusActions}>
                      <Button type="primary" onClick={handleChangeAddShippingModalVisible}>发货</Button>
                    </div>
                  </>
                }
                {
                  (_.isEqual(status, Shipped) || _.isEqual(status, AwaitingPickup)) && <>
                    <Title level={4}>商家已发货，等待交易成功</Title>
                    <Text>买家如在<Text type="danger">7天内</Text>没有申请退款，交易将自动完成。</Text>
                    <div className={classes.orderStatusActions}>
                      <Button type="link" onClick={handleChangeEditShippingModalVisible}>修改物流</Button>
                      <Button>延长收货</Button>
                    </div>
                  </>
                }
                {
                  (status === Cancelled) && <>
                    <Title level={4}>交易取消</Title>
                    <Text>{order.cancelReason}</Text>
                  </>
                }
                <Row gutter={[0, 16]} align="middle">
                  <Col span={24}>
                    <Button className={classes.orderStaffNotesButton}
                            onClick={handleChangeStaffNotesModalVisible}
                            type="link"
                            size="small">备注</Button>
                    <Rate allowClear/>
                  </Col>
                </Row>
              </Col>
              <Col span={14}>
                {status !== Cancelled &&
                status !== Completed && <>
                  <OrderStatusSteps
                    status={status}
                    placedTime={order.placedTime}
                    paidTime={order.paidTime}
                    shippedTime={order.shippedTime}/>
                </>
                }
              </Col>
            </Row>
            <Row gutter={[24, 24]} className={classes.orderNotes} align="top">
              <Col span={24}>
                {
                  order.staffNotes &&
                  <Descriptions>
                    <Descriptions.Item label="订单备注">
                      {order.staffNotes}
                    </Descriptions.Item>
                  </Descriptions>
                }
                <Descriptions className={classes.orderTransactionAlter}>
                  <Descriptions.Item label="系统提示">
                    交易成功后，系统将把货款结算至你的店铺账户余额，你可申请提现；<br/>
                    请及时关注你发出的包裹状态，确保能配送至买家手中；<br/>
                    如果买家表示未收到货或者货物有问题，请及时联系买家积极处理，友好协商；<br/>
                  </Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>
            <OrderCancelModal visible={cancelModalVisible}
                              orderId={orderId}
                              onCancel={handleChangeCancelModalVisible}
                              onCancelled={() => {
                                handleChangeCancelModalVisible()
                                refreshOrder()
                              }}/>
            <OrderDiscountsModal visible={discountsModalVisible}
                                 orderId={orderId}
                                 items={order.items}
                                 onCancel={handleChangeDiscountsModalVisible}
                                 onChanged={() => {
                                   handleChangeDiscountsModalVisible()
                                   refreshOrder()
                                 }}/>
            <OrderStaffNotesModal
              visible={staffNotesModalVisible}
              orderId={orderId}
              staffNotes={order.staffNotes}
              loading={staffNotesModalLoading}
              onCancel={handleChangeStaffNotesModalVisible}
              onSave={handSaveStaffNotes}/>
            <AddOrderShippingModal
              visible={addShippingModalVisible && (order.status !== Shipped && order.status !== AwaitingPickup)}
              orderId={orderId}
              shippingAddress={shippingAddress}
              items={tableItems}
              onCancel={handleChangeAddShippingModalVisible}
              onShipped={refreshOrder}/>
            <EditOrderShippingModal
              visible={editShippingModalVisible}
              orderId={orderId}
              shipments={order.shipments}
              onCancel={handleChangeEditShippingModalVisible}
              onSaved={() => {
                handleChangeEditShippingModalVisible()
                refreshOrder()
              }}/>
            <OrderShipments shipments={order.shipments}/>
            <Row gutter={[24, 24]} style={{
              ...(_.isEmpty(order.shipments) ? { marginTop: "12px" } : {}),
            }}>
              <Col span={24}>
                <Row className={classes.orderShippingAddress}>
                  <Col span={6}>
                    <Descriptions title="收货人信息" size="small" column={1}>
                      <Descriptions.Item label="收货人"
                                         children={`${shippingAddress.lastName}${shippingAddress.firstName}`}/>
                      <Descriptions.Item label="联系电话" children={shippingAddress.mobile}/>
                      <Descriptions.Item label="收货地址"
                                         children={`${shippingAddress.province}${shippingAddress.city}${shippingAddress.county} ${shippingAddress.address}`}/>
                    </Descriptions>
                  </Col>
                  <Col span={6}>
                    <Descriptions title="配送信息" column={1}>
                      <Descriptions.Item label="配送方式">快递</Descriptions.Item>
                      {shippedTime && <Descriptions.Item label="发货时间" children={shippedTime}/>}
                    </Descriptions>
                  </Col>
                  <Col span={6}>
                    <Descriptions title="支付信息" column={1}>
                      <Descriptions.Item label="支付状态" children={renderPaymentStatus()}/>
                      <Descriptions.Item label="支付方式" children={renderPaymentMethod()}/>
                      {order.paidTime && <Descriptions.Item label="支付时间" children={order.paidTime}/>}
                    </Descriptions>
                  </Col>
                  <Col span={6}>
                    <Descriptions title="买家信息" column={1}>
                      <Descriptions.Item label="买家">15688477267</Descriptions.Item>
                      <Descriptions.Item label="买家留言">-</Descriptions.Item>
                    </Descriptions>
                  </Col>
                </Row>
              </Col>
            </Row>
            <Row gutter={[24, 24]} className={classes.orderItems}>
              <Col span={24}>
                <Table rowKey="id"
                       columns={orderItemsColumns}
                       dataSource={tableItems}
                       pagination={false}/>
              </Col>
            </Row>
            <Row gutter={[24, 0]} justify="end">
              <Col span={8}>
                <Descriptions column={1} className={classes.orderPrices}>
                  <Descriptions.Item label="商品总价" children={`￥${order.subtotalAmount}`}/>
                  <Descriptions.Item label="运费" children={`￥${order.totalShippingCost}`}/>
                  <Descriptions.Item label="优惠" children={`￥${order.totalDiscountAmount}`}/>
                  <Descriptions.Item label="实收金额" className={classes.orderTotalPrice}
                                     children={`￥${order.totalAmount}`}/>
                </Descriptions>
              </Col>
            </Row>
          </Card>
        </Spin>
      </Page.Content>
    </div>
  )
}
